﻿using ELearning.BLL;
using ELearning.Common;
using ELearning.Common.Extensions;
using ELearning.Common.Model;
using ELearning.Models;
using ELearning.Models.ViewModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using System.Web.Http;

namespace ELearning.API.Controllers
{
    /// <summary>
    /// 题库
    /// </summary>
    public class QuestionController : BaseApiController
    {

        EQuestionService qservice = new EQuestionService();
        EDictionaryService dictionaryService = new EDictionaryService();
        RPaperQuestionService pqService = new RPaperQuestionService();

        /// <summary>
        /// 获取题库、科目、年级、等级……集合
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost, Route("api/question/getQBankList")]
        public ServiceResponse<object> GetQBankList(QuestionRequest req)
        {
            //&& u.Owner == CurrentUserModel.UserId
            Expression<Func<EQuestion, bool>> whereLamdba = (u) => u.IsDelete == false;

            if (!string.IsNullOrEmpty(req.Question.SubjectCode))
            {
                var subjects = dictionaryService.GetDicInParent(req.Question.SubjectCode).Select(x => x.TypeCode).ToList();
                whereLamdba = whereLamdba.And(u => subjects.Contains(u.SubjectCode));
            }
            if (!string.IsNullOrEmpty(req.Question.QContent))
                whereLamdba = whereLamdba.And(u => u.QContent.Contains(req.Question.QContent));
            if (req.Question.QType != -1)
                whereLamdba = whereLamdba.And(u => u.QType == req.Question.QType);
            if (req.Question.QGroup != -1)
                whereLamdba = whereLamdba.And(u => u.QGroup == req.Question.QGroup);
            if (req.NotInIDs.Count > 0)
            {
                whereLamdba = whereLamdba.And(u => !req.NotInIDs.Contains(u.ID));
            }
            var res = qservice.FindPageList(req.Page, req.PageSize, out int total, req.OrderBy, req.IsAsc ? "asc" : "desc", whereLamdba).ToList();

            var re = new { views = res, TotalCount = total };

            return ServiceResponse<object>.SuccessResponse(re);
        }

        /// <summary>
        /// 获取题库中所有题目
        /// 1-考试题库
        /// 2-问卷题库
        /// </summary>
        /// <returns></returns>
        [HttpGet, Route("api/question/getQBankAll")]
        public ServiceResponse<List<EQuestion>> GetQBankAll(int qGroup)
        {
            var res = qservice.GetQBankAll(qGroup);

            return ServiceResponse<List<EQuestion>>.SuccessResponse(res);
        }

        /// <summary>
        /// 获取题目、科目、年级、等级……集合-ByID
        /// </summary>
        /// <param name="qid"></param>
        /// <returns></returns>
        [HttpGet, Route("api/question/getQByID")]
        public ServiceResponse<EQuestion> GetQByID(string qid)
        {
            var id = Guid.Parse(qid);

            var res = qservice.Find(x => x.IsDelete == false && x.ID == id);

            return ServiceResponse<EQuestion>.SuccessResponse(res);
        }

        /// <summary>
        /// 新增题目
        /// </summary>
        /// <param name="qt"></param>
        /// <returns></returns>
        [HttpPost, Route("api/question/insertQuestion")]
        public ServiceResponse<bool> InsertQuestion(EQuestion qt)
        {
            var exits = qservice.Find(x => x.IsDelete == false && x.QContent == qt.QContent);
            if (exits != null) return ServiceResponse<bool>.SuccessResponse("添加失败，题目名称已存在", false);
            qt.ID = Guid.NewGuid();
            qt.OrgCode = CurrentUserModel.OrgCode;
            qt.Owner = CurrentUserModel.UserId;
            qt.Creater = qt.Modifyer = CurrentUserModel.LoginName;
            qt.CreateTime = qt.ModifyTime = DateTime.Now;
            qt.IsDelete = false;
            var res = qservice.Add(qt);
            if (res != null) return ServiceResponse<bool>.SuccessResponse("添加题目成功", true);
            else return ServiceResponse<bool>.ErrorResponse("添加题目失败", false);
        }

        /// <summary>
        /// 新增题目：组卷页面新增操作
        /// 需返回新增的数据
        /// </summary>
        /// <param name="qt"></param>
        /// <returns></returns>
        [HttpPost, Route("api/question/insertQuestionByChoose")]
        public ServiceResponse<object> InsertQuestionByChoose(EQuestion qt)
        {
            var exits = qservice.Find(x => x.IsDelete == false && x.QContent == qt.QContent);
            if (exits != null) return ServiceResponse<object>.SuccessResponse("添加失败，题目名称已存在", false);
            qt.ID = Guid.NewGuid();
            qt.OrgCode = CurrentUserModel.OrgCode;
            qt.Owner = CurrentUserModel.UserId;
            qt.Creater = qt.Modifyer = CurrentUserModel.LoginName;
            qt.CreateTime = qt.ModifyTime = DateTime.Now;
            qt.IsDelete = false;
            var res = qservice.Add(qt);
            if (res != null) return ServiceResponse<object>.SuccessResponse("添加题目成功", res);
            else return ServiceResponse<object>.ErrorResponse("添加题目失败", false);
        }

        /// <summary>
        /// 导入题库
        /// </summary>
        /// <param name="qs"></param>
        /// <param name="qGroup"></param>
        /// <returns></returns>
        [HttpPost, Route("api/question/importBank")]
        public ServiceResponse<object> ImportBank(List<EQuestion> qs, int qGroup)
        {
            try
            {
                var allq = qservice.FindList(x => !x.IsDelete).Select(m => m.QContent).ToList();

                var subjects = dictionaryService.GetDicNoParent("Subject");
                List<TreeViewModel> lists = new List<TreeViewModel>();
                TreeViewModel model = null;
                foreach (var x in subjects)
                {
                    model = new TreeViewModel();
                    model.id = x.ID;
                    model.ParentID = x.ParentID;
                    model.label = x.TypeName;
                    model.value = x.TypeCode;
                    model.children = null;
                    lists.Add(model);
                }

                var tree = RecursionExtensions.SubjectTreeF(lists);

                var succe = new List<EQuestion>();
                var faile = new List<EQuestion>();
                foreach (var qt in qs)
                {
                    qt.ID = Guid.NewGuid();
                    qt.OrgCode = CurrentUserModel.OrgCode;
                    qt.Owner = CurrentUserModel.UserId;
                    qt.Creater = qt.Modifyer = CurrentUserModel.LoginName;
                    qt.CreateTime = qt.ModifyTime = DateTime.Now;
                    qt.Difficulty = 0;
                    qt.OpenLevel = 3;
                    qt.QState = 4;
                    qt.Composed = false;
                    qt.QGroup = qGroup;
                    qt.IsDelete = false;
                    var suj = subjects.Find(x => x.TypeName == qt.Extend1);
                    qt.SubjectCode = suj == null ? null : suj.TypeCode;
                    if (qt.SubjectCode != null)
                    {
                        var SubjectName = tree.Find(x => x.label == qt.Extend1);
                        List<string> arrName = new List<string>();
                        RecursionExtensions.GetChildrenNode(SubjectName, ref arrName);
                        arrName.Reverse();
                        qt.SubjectName = string.Join("-", arrName);
                    }
                    var tag = true;
                    if (string.IsNullOrEmpty(qt.QContent))
                    {
                        qt.Extend2 = "题目名称不可为空；";
                        tag = false;
                    }
                    if (qt.Extend1 == null)
                    {
                        qt.Extend2 += "分类不可为空；";
                        tag = false;
                    }
                    else
                    {
                        if (qt.SubjectCode == null)
                        {
                            qt.Extend2 += "分类超出范围；";
                            tag = false;
                        }
                    }
                    if (string.IsNullOrEmpty(qt.QAnswer) && qt.QGroup == 1)
                    {
                        qt.Extend2 = "题目答案不可为空；";
                        tag = false;
                    }
                    if ((qt.QType == 1 || qt.QType == 2) && qt.QGroup == 1)
                    {
                        if (string.IsNullOrEmpty(qt.ChoiceA))
                        {
                            qt.Extend2 = "选项A不可为空；";
                            tag = false;
                        }
                        if (string.IsNullOrEmpty(qt.ChoiceB))
                        {
                            qt.Extend2 = "选项B不可为空；";
                            tag = false;
                        }
                        if (string.IsNullOrEmpty(qt.ChoiceC))
                        {
                            qt.Extend2 = "选项C不可为空；";
                            tag = false;
                        }
                        if (string.IsNullOrEmpty(qt.ChoiceD))
                        {
                            qt.Extend2 = "选项D不可为空；";
                            tag = false;
                        }
                    }
                    if (allq.Exists(x => x == qt.QContent))
                    {
                        qt.Extend2 += "题目名称重复；";
                        tag = false;
                    }
                    if ((qt.QType < 1 || qt.QType > 3) && qt.QGroup == 1)
                    {
                        qt.Extend2 += "题型超出范围；";
                        tag = false;
                    }
                    if ((qt.QType < 1 || qt.QType > 2) && qt.QGroup == 2)
                    {
                        qt.Extend2 += "题型超出范围；";
                        tag = false;
                    }
                    var nAnswer = "";
                    var OKArr = new List<string> { "A", "B", "C", "D" };
                    if (!string.IsNullOrEmpty(qt.QAnswer) && qt.QGroup == 1)
                    {
                        switch (qt.QType)
                        {
                            case 1:
                                nAnswer = qt.QAnswer;
                                if (!OKArr.Exists(x => x == nAnswer))
                                {
                                    nAnswer = "";
                                    tag = false;
                                }
                                break;
                            case 2:
                                var str = qt.QAnswer.ToCharArray();
                                Array.Sort(str);
                                nAnswer = string.Join(",", str);
                                foreach (var a in str)
                                {
                                    if (!OKArr.Exists(x => x == a.ToString()))
                                    {
                                        nAnswer = "";
                                        tag = false;
                                        break;
                                    }
                                }
                                break;
                            case 3:
                                if (qt.QAnswer == "正确") nAnswer = "1";
                                else if (qt.QAnswer == "错误") nAnswer = "0";
                                else nAnswer = "";
                                break;
                            default:
                                nAnswer = "";
                                break;
                        }
                        if (qt.QType > 0 && qt.QType < 4 && nAnswer == "")
                        {
                            qt.Extend2 += "答案超出范围；";
                            tag = false;
                        }
                    }
                    if (tag)
                    {
                        qt.QAnswer = nAnswer;
                        succe.Add(qt);
                    }
                    else faile.Add(qt);
                }

                var r = qservice.Adds(succe);

                var list = new { succeed = succe, failed = faile, status = true };

                var msg = ("添加题目成功" + r + "个" + "；失败" + (qs.Count - r) + "个");
                return ServiceResponse<object>.SuccessResponse(msg, list);
            }
            catch (Exception ex)
            {
                var list = new { status = false };
                return ServiceResponse<object>.SuccessResponse("题库导入失败，请检查模板", list);
            }
        }

        /// <summary>
        /// 更新题目
        /// </summary>
        /// <param name="qt"></param>
        /// <returns></returns>
        [HttpPost, Route("api/question/updateQuestion")]
        public ServiceResponse<bool> UpdateQuestion(EQuestion qt)
        {
            //if (qt.Owner != CurrentUserModel.UserId) return ServiceResponse<object>.SuccessResponse("更新失败，该题目已被使用", false);
            //if (qt.Composed == true) return ServiceResponse<object>.SuccessResponse("更新失败，该题目已被使用", false);
            var exits = qservice.Find(x => x.IsDelete == false && x.QContent == qt.QContent && x.ID != qt.ID);
            if (exits != null) return ServiceResponse<bool>.SuccessResponse("更新失败，题目名称已存在", false);
            qt.Modifyer = CurrentUserModel.LoginName;
            qt.ModifyTime = DateTime.Now;

            var res = qservice.Update(qt);
            if (res) return ServiceResponse<bool>.SuccessResponse("更新题目成功", true);
            else return ServiceResponse<bool>.ErrorResponse("更新题目失败", false);
        }

        /// <summary>
        /// 删除题目
        /// </summary>
        /// <param name="qt"></param>
        /// <returns></returns>
        [HttpPost, Route("api/question/deleteQuestion")]
        public ServiceResponse<bool> DeleteQuestion(EQuestion qt)
        {
            // if (qt.Owner != CurrentUserModel.UserId) return ServiceResponse<object>.SuccessResponse("不可删除，您不是此题目的创建者", false);
            if (qt.Composed == true) return ServiceResponse<bool>.SuccessResponse("删除失败，该题目已被使用", false);
            qt.Modifyer = CurrentUserModel.LoginName;
            qt.ModifyTime = DateTime.Now;
            qt.IsDelete = true;
            var res = qservice.Update(qt);
            if (res) return ServiceResponse<bool>.SuccessResponse("删除题目成功", true);
            else return ServiceResponse<bool>.ErrorResponse("删除题目失败", false);
        }

    }
}